﻿using Grow.Db.Repository;
using Grow.Db.UnitOfWork;
using Grow.EventBus.Cap.Enum;
using Grow.EventBus.Cap.SubscriberEventData;
using Grow.Module.Service;
using Grow.Scheduler.Job;

namespace Grow.EventBus.Cap.Job
{
    public class ExpirerSubscriberEventDataJob : JobBase
    {
        private readonly IUnitOfWorkManager _unitOfWorkManager;
        private readonly IRepository<SubscriberEventDataEntity> _subscriberEventDataRepository;
        public ExpirerSubscriberEventDataJob(IServiceContext serviceContext) : base(serviceContext)
        {
            _unitOfWorkManager = serviceContext.GetRequiredService<IUnitOfWorkManager>();
            _subscriberEventDataRepository = serviceContext.GetRequiredService<IRepository<SubscriberEventDataEntity>>();
        }

        public override async Task ExecuteAsync(CancellationToken cancellationToken)
        {
            var now = DateTimeOffset.Now;

            var subscriberEventDataEntitys = await _subscriberEventDataRepository.GetSelectRepository().Where(a =>
                a.ExpireTime < now && a.ExpireTime != null
                && a.EventDataStatus == EventDataStatusEnum.Success
               ).ToListAsync(cancellationToken);

            foreach (var subscriberEventDataEntity in subscriberEventDataEntitys)
            {
                await _subscriberEventDataRepository.RemoveAsync(subscriberEventDataEntity, cancellationToken);
            }
            await _unitOfWorkManager.CommitAsync(cancellationToken);
        }
    }
}
